<template>
	<view class="video-wrap">
		<view class="video-detail">
			<video class="videoitem" :src="detailobj.resultUrl" :enable-play-gesture='true' :controls="true"
				v-if="detailobj.resultUrl">
			</video>
			<view class="bacimg" v-else-if="status == 2">
				<!-- 生成中 -->
				<view class="bacc">
					<view class="icon" style="background-color: #00aaff;">
						<u-loading-icon color="#fff"></u-loading-icon>
					</view>
					<view class="title">
						视频生成中
					</view>
					<view class="time">
						预计剩余时间: {{detailobj.taskProcessTime=='00:00'?'00.01':detailobj.taskProcessTime}}
					</view>
				</view>
			</view>
			<view class="bacimg" v-else-if="status == 1">
				<!-- 排队中 -->
				<view class="bacc">
					<view class="icon" style="background-color: #ffaa00;">
						<u-loading-icon color="#fff"></u-loading-icon>
					</view>
					<view class="title">
						视频排队中
					</view>
					<view class="time">
						当前位置: {{detailobj.queuePosition}}
					</view>
				</view>
			</view>
			<view class="" v-else-if="status == 4">
				<!-- 生成失败 -->
				暂无视频
			</view>

		</view>
		<view class="video-content">
			<view class="info-title" style="margin-bottom:5px;">
				<view class="content-wrapper">
					<view class="content-text">
						{{detailobj.context && detailobj.context.length > 35 &&  !isExpanded  ? detailobj.context.slice(0, 35) : detailobj.context|| '' }}
						<view v-if="detailobj.context &&  detailobj.context.length>35" class="toggle-btn"
							@click="toggleExpand">
							{{ isExpanded ? '收起' : '...展开' }}
						</view>
					</view>
				</view>
				<!-- {{}} -->
			</view>
			<view class="video-data">
				<view>{{detailobj.insertTime}}</view>
				<!-- <view>·</view> -->
				<!-- <view>1080P</view> -->
				<view v-if="status == 3">·</view>
				<view v-if="status == 3">{{durationfn(detailobj.videoDuration)}}</view>
				<!-- <view v-show="status ==3">· 20.89MB</view> -->
			</view>
			<view class="video-status">
				<!-- 生成中的状态 -->
				<view class="status-item prog" v-if="status == 2">
					<view class="status-title">
						<u-icon name="hourglass-half-fill" size="17" color="#3B82F6"></u-icon>
						<span style="margin-left: 5px;">视频正在生成中</span>
					</view>
					<view class="status-dasc">预计总用时 <text style="margin-left:10px;">{{estimatedTime}}</text></view>
				</view>
				
			</view>
			<!-- 排队中的状态 -->
			<view class="status-item queue" v-if="status == 1">
				<view class="status-title">
					<u-icon name="clock-fill" size="17" color="#F97316"></u-icon>
					<span style="margin-left: 5px;">视频正在排队等待处理</span>
				</view>
				<view class="status-dasc">当前队列位置: <text style="margin-left:10px;">{{detailobj.queuePosition}}</text>
					<!-- 	 , 预计开始处理时间: <text
							style="margin-left:10px;">00:59</text> -->
				</view>
				<view class="status-urgent">
					<!-- <view class="status-plain">普通优先级</view> -->
					<!-- <view class="status-upgrade">升级为加急处理</view> -->
				</view>
			</view>
			<!-- 失败的状态 -->
			<view class="status-item error" v-if="status ==4">
				<view class="status-title">
					<u-icon name="info-circle-fill" size="17" color="#EF4444"></u-icon>
					<span style="margin-left: 5px;">视频生成失败</span>
				</view>
				<view class="status-dasc">生成视频任务失败 <text
						style="color:#EF4444;margin-left:10px;font-weight:bold;">视频文件错误</text></view>
			</view>
			<!-- 已完成的状态 -->
			<view class="status-item success" v-if="status == 3">
				<view class="status-title">
					<u-icon name="checkbox-mark" size="17" color="#00aa00"></u-icon>
					<span style="margin-left: 5px;">视频生成成功</span>
					</view>
				<view class="status-dasc">当前剩余积分: <text style="margin-left:10px;color:#F97316;font-weight:bold;">
						{{userInfo.pointsNum?userInfo.pointsNum:0}}</text></view>
				<view class="status-dasc">可下载视频文件，下载将扣除10积分</view>
			</view>

		</view>
		<!-- 生成参数 -->
		<view class="video-list-info">
			<view class="info-title">生成参数</view>
			<view class="video-info">
				<view class="info-row">
					<view class="row-item left-item">素材类型</view>
					<view class="row-item right-item">{{detailobj.taskType==2?'视频':'图片'}}</view>
				</view>
				<view class="info-row">
					<view class="row-item left-item">素材数量</view>
					<view class="row-item right-item">1个</view>
				</view>
				<view class="info-row">
					<view class="row-item left-item">音色选择</view>
					<view class="row-item right-item">{{detailobj.timbreType==1?'系统音色':'自定义音色'}}
						<span v-if='detailobj.timbreType==1'>({{detailobj.timbreName}})</span>
					</view>
				</view>
				<view class="info-row">
					<view class="row-item left-item">视频比例</view>
					<view class="row-item right-item">
						{{detailobj.width?detailobj.width:4}}:{{detailobj.height?detailobj.height:3}}
					</view>
				</view>
				<!-- <view class="info-row">
						<view class="row-item left-item">图片背景</view>
						<view class="row-item right-item">自定义背景</view>
					</view> -->
				<view class="info-row">
					<view class="row-item left-item">分辨率</view>
					<view class="row-item right-item">720P</view>
				</view>
			</view>
		</view>
		<!-- 按钮 -->
		<view class="video-btn">
			<!-- 已完成 任务 分状态 是否下载 为下载 显示下载按钮  已下载 显示 分享到视频号-->
			<!-- 生成中 任务 显示 取消生成 和 重新生成 两个 -->
			<!-- 队列中 任务 显示 取消生成 和 重新生成 两个 -->
			<view class="video-success-btn" v-if="status == 3">
				<button class="success-btn" @click="download">下载视频</button>
				<!-- <button class="success-btn" v-if="isDownLoad">分享到视频号</button> -->
			</view>
			<view class="video-plian-btn" v-else>
				<!-- <button class="plain-btn cancel-color">取消生成</button> -->
				<!-- <button class="plain-btn align-color">重新生成</button> -->
			</view>
		</view>
	</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// isDownLoad: false,
				status: "",
				id: '',
				detailobj: {},
				userInfo: {},
				isExpanded: false,
				timer: null
			};
		},
		components: {},
		// onLoad(options) {
		// 		this.userid = options.userid
		// 		this.followslist()
		// 	},
		beforeDestroy() {
			this.clearTimers();
			console.log(123123);
			// const eventChannel = this.getOpenerEventChannel()
			// eventChannel.emit('Data', {
			// 	data: true
			// })
		},
		computed: {
			estimatedTime() {
				if (!this.detailobj.context) {
					return ''
				}
				// console.log(this.detailobj.context);
				// 获取字数
				const wordCount = this.detailobj.context.length;

				// 确保最低时间为20秒
				let timeInSeconds;

				// 根据字数计算时间
				if (wordCount <= 18) {
					timeInSeconds = 20;
				} else if (wordCount <= 100) {
					timeInSeconds = (wordCount - 18) * 0.35 + 20; // 线性增长
				} else if (wordCount <= 200) {
					timeInSeconds = (wordCount - 18) * 0.5 + 50; // 稍快增长
				} else if (wordCount <= 300) {
					timeInSeconds = (wordCount - 18) * 0.6 + 100; // 增速加快
				} else {
					timeInSeconds = (wordCount - 18) * 0.8 + 120; // 超过300字后时间快速增长
				}

				// 确保时间不低于20秒
				timeInSeconds = Math.max(timeInSeconds, 20);

				// 计算分钟和秒数
				let minutes = Math.floor(timeInSeconds / 60);
				let seconds = Math.round(timeInSeconds % 60);

				return `${minutes} 分 ${seconds} 秒`;
			},
			// aspectRatio() {
			// 	return this.getAspectRatio(this.width, this.height);
			// }
		},
		onLoad(query) {
			const obj = JSON.parse(decodeURIComponent(query.type))
			console.log(obj);
			this.id = obj.id

			console.log(this.status);
			this.videodetail()
			/**
			 * status 定义
			  1 待处理  2 处理中   4 任务失败
			 已完成 3
			*/
			// this.status = obj.type;
		},
		mounted() {
			this.userInfo = uni.getStorageSync('digital_aI_key')
		},
		watch: {

		},
		methods: {
			toggleExpand() {
				this.isExpanded = !this.isExpanded;
			},
			download() {
				uni.showLoading({
					title: "下载中...",
					mask: true
				});
				uni.downloadFile({
					url: this.detailobj.resultUrl, //仅为示例，并非真实的资源
					success: (res) => {
						if (res.statusCode === 200) {
							this.saveVideoToPhotosAlbum(res.tempFilePath);
						}
					},
					fail: (err) => {
						console.error('下载失败', err);
						uni.showToast({
							title: '下载失败',
							icon: 'none'
						});
					}
				});

			},
			saveVideoToPhotosAlbum(tempFilePath) {
				wx.saveVideoToPhotosAlbum({
					filePath: tempFilePath,
					success: () => {
						uni.hideLoading();
						uni.showToast({
							title: '下载成功',
							icon: 'success',
						});
						console.log('下载成功');
					},
					fail: (err) => {
						console.error('保存失败', err);

						// 处理权限拒绝的情况
						if (err.errMsg.includes('auth deny')) {
							this.showAuthSetting();
						} else {
							wx.showToast({
								title: '保存失败',
								icon: 'none'
							});
						}
					}
				});
			},

			durationfn(ms) {
				// 将毫秒转换为秒
				let seconds = Math.floor(ms / 1000);

				// 计算分钟和剩余的秒数
				let minutes = Math.floor(seconds / 60);
				let remainingSeconds = seconds % 60;

				// 格式化输出 MM:SS
				return `${minutes < 10 ? '0' + minutes : minutes}:${remainingSeconds < 10 ? '0' + remainingSeconds : remainingSeconds}`;
			},
			gcd(a, b) {
				while (b !== 0) {
					let temp = b;
					b = a % b;
					a = temp;
				}
				return a;
			},
			// 获取宽高比
			getAspectRatio(width, height) {

				let divisor = this.gcd(width, height);
				let aspectWidth = width / divisor;
				let aspectHeight = height / divisor;
				console.log(aspectWidth, aspectHeight);
				return `${aspectWidth?aspectWidth:4}:${aspectHeight?aspectHeight:3}`;
			},
			videodetail() {
				this.$request(`/task/getTaskDetail/${this.id}`, 'get').then(
					res => {
						this.detailobj = res.data.data
						this.status = res.data.data.taskState

						if (this.status == 1 || this.status == 2) {
							console.log('开始加载');
							this.timefn();
						} else {
							console.log('不用加载');
							this.clearTimers()
						}
						// console.log(res);
					})
			},
			timefn() {
				// 检查是否需要请求特定状态的定时器
				const checkAndRequest = () => {
					if (this.status != 1 && this.status != 2) {
						console.log('结束');
						this.clearTimers()
						return;
					}
					// 如果定时器不存在，则创建
					if (!this.timer) {
						this.timer = setInterval(() => {
							if (this.status != 1 && this.status != 2) {
								console.log('结束');
								this.clearTimers()
								return;
							}
							this.videodetail();
						}, 5000);
					}
				};
				// 初始检查并启动定时器
				checkAndRequest('timer');
			},
			clearTimers() {
				if (this.timer) {
					clearInterval(this.timer);
					this.timer = null;
				}

			},
		}
	};
</script>

<style scoped lang="scss">
	.bacimg {
		height: 220px;
		background-image: url('https://ivu06wjqra.dy.takin.cc/human/process/26.png');
		background-size: 100% 100%;
	}

	.bacc {
		height: 100%;
		background-color: rgba(0, 0, 0, 0.2);
		color: #f5f5f5;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		.icon {
			display: flex;
			align-items: center;
			justify-content: center;
			border-radius: 50%;
			height: 50px;
			width: 50px;

		}

		.title {
			margin: 20px 0 10px;
			font-size: 34rpx;
		}

		.time {
			font-size: 28rpx;
		}
	}

	/* 外层容器，确保文本和按钮同行 */
	.content-wrapper {
		display: inline-block;
		/* 关键 */
		max-width: 100%;
		/* 防止溢出 */
	}

	/* 文本样式 */
	.content-text {
		/* font-size: 27rpx; */
		display: inline;
		/* 关键：让文本和按钮同行 */
		line-height: 1.5;
		/* 行高 */
		vertical-align: top;
		/* 避免按钮下沉 */
		position: relative;
	}

	/* 展开/收起按钮（强制同行 + 不换行） */
	.toggle-btn {
		z-index: 10;
		display: inline-block;
		/* 关键 */
		color: #F97316;
		margin-left: 3px;
		/* 和文字间隔 */
		vertical-align: top;
		/* 避免下沉 */
		white-space: nowrap;
		/* 强制不换行 */
	}

	.video-detail {
		width: 100%;
		/* height: 100%; */
		height: 220px;
		text-align: center;
		// line-height: 220px;
		font-size: 30px;
		background-color: #e2e2e2;
		color: #6B7280;

	}

	.videoitem {
		width: 100%;
		height: 100%;
	}

	.video-content {
		width: 100%;
		height: 100%;
		margin-top: 10px;
		box-sizing: border-box;
		padding: 10px 20px;
	}

	.video-data {
		display: flex;

	}

	.video-data view {
		margin-right: 5px;
		font-size: 14px;
		color: #6B7280;
	}

	.status-item {
		width: 100%;
		/* height:70px; */
		margin-top: 10px;
		border-radius: 10px;
		box-sizing: border-box;
		padding: 10px 20px;

	}

	.status-title {
		display: flex;
		align-items: center;
		font-size: 15px;
		color: #1E293B;
		font-weight: 600;
	}

	.status-dasc {
		margin-top: 10px;
		font-size: 14px;
		color: #64748B;
	}

	.status-urgent {
		margin-top: 10px;
		display: flex;
		justify-content: space-between;
		font-size: 14px;
	}

	.status-urgent .status-plain {
		padding: 5px 5px;
		color: #374151;
		border-radius: 5px;
		background-color: #E5E7EB;
	}

	.status-urgent .status-upgrade {
		padding: 5px 5px;
		color: #3B82F6;
		font-size: 15px;
		font-weight: bold;
	}

	.video-list-info {
		padding: 0 20px;
		width: calc(100% - 40px);
		height: auto;
		margin-top: 10px;
	}

	.info-title {
		font-size: 16px;
		font-weight: bold;
		color: #000;
	}

	.video-info {
		margin-top: 10px;
		display: flex;
		flex-direction: column;
	}

	.info-row {
		display: flex;
		justify-content: space-between;
		width: 100%;
	}

	.row-item {
		flex: 1;
		padding: 5px 10px;
		box-sizing: border-box;
		font-size: 14px;
	}

	.left-item {
		text-align: left;
		color: #64748B;
	}

	.right-item {
		text-align: right;
		color: #1E293B;
		font-weight: bold;
	}

	.video-btn {
		position: fixed;
		left: 0;
		bottom: 20px;
		right: 0;
		box-sizing: border-box;
		padding: 0 20px;
		width: 100%;
		height: 40px;
		/* box-sizing: border-box;
		padding:0 10px; */
		/* background-color:#f0f; */
	}

	.video-success-btn {
		width: 100%;
		height: 40px;
		/* box-sizing:border-box;
		padding:0 20px; */
	}

	.success-btn {
		width: 100%;
		height: 40px;
		border: none;
		outline: none;
		border-radius: 20px;
		font-size: 15px;
		color: #fff;
		/* border:1px solid #D1D5DB; */
		background-color: #F97316;
	}

	/* .border{
		border:1px solid #D1D5DB;
	} */
	.video-plian-btn {
		display: flex;
		justify-content: space-between;
	}

	.plain-btn {
		width: 49%;
		height: 40px;
		border: none;
		outline: none;
		border-radius: 20px;
		font-size: 15px;
	}

	.cancen-color {
		background-color: #fff;
	}

	.align-color {
		color: #fff;
		background-color: #F97316;
	}

	button::after {
		border: none;
	}
</style>
<style>
	.prog {
		background-color: #EFF6FF;
	}

	.queue {
		background-color: #FEFCE8;
	}

	.success {
		background-color: #F0FDF4;
	}

	.error {
		background-color: #FEE2E2;
	}
</style>